<?php

require '../data/data.php';

//只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	header('HTTP/1.1 405 Method Not Allowed');
	return;
}

//开启session
session_start();

//接收注册信息
$username = input('username');
$password = input('password');
$pwdConfirm = input('pwdConfirm');

//正则表单式验证信息
$usernameRegexp = '/[\w\x{4e00}-\x{9fa5}]/u';
$passwordRegexp = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[.(){}%]).*$/';

//初始化错误包
$isError = false;
$errorBag = [
	'username' => '',
	'password' => '',
	'pwdConfirm' => '',
];

//判断填写的注册信息是否符合规范
if (trim($username) === '') {
	$isError = true;
	$errorBag['username'] = '用户名不能为空';
}elseif (preg_match($usernameRegexp, $username) === 0) {
	$isError = true;
	$errorBag['username'] = '用户名只能由数字汉字和大小写字母和下划线组成';
}elseif (strlen(trim($password)) < 6) {
	$isError = true;
	$errorBag['password'] = '密码不能小于6位';
}elseif (!preg_match($passwordRegexp, $password)) {
	$isError = true;
	$errorBag['password'] = '密码必须包含大小写字母，数字和特殊字符';
}elseif (trim($pwdConfirm) === '') {
	$isError = true;
	$errorBag['pwdConfirm'] = '请确认密码';
}

//判断用户名是否已经被注册
$sql = 'select id from `users` user_name = ?';
$data = query($sql, [$username]);
if (count($data) > 0) {
	$isError = ture;
	$errorBag['username'] = '该用户名已经被注册';
}

//将错误包返回到注册页面
if ($isError) {
	$_SESSION['is_error'] = $isError;
	$_SESSION['error_bag'] = $errorBag;
	header('Location:../register.php');
	return;
}

//验证完毕，写入数据库
//对用户密码进行加密
$password = password_hash($password, PASSWORD_BCRYPT);
$sql = 'insert into `users` (user_name, password, register_time) values (?, ?, now())';
$args = [$username, $password];
execute($sql, $args);
header('Location:../login.php');

function input($var)
{
	if (isset($_POST[$var]) && !empty($_POST[$var])) {
		$var = htmlspecialchars(trim($_POST[$var]));
	}else $var = '';
	return $var;
}